package src

import (
	"fmt"
	"time"

	"gitee.com/haifengat/goctp"
	ctp "gitee.com/haifengat/goctp/lnx"
	"github.com/sirupsen/logrus"
)

var t = ctp.NewTrade()
var reloginTimes int

func startTrade() {
	logrus.Infoln("connected to trade...")

	var chConnected = make(chan bool)
	t.RegOnFrontConnected(func() {
		logrus.Infoln("trade connected")
		chConnected <- true
		go t.ReqLogin(investorID, password, brokerID, appID, authCode)
	})
	t.RegOnFrontDisConnected(func(reason int) {
		logrus.Info("trade disconnected ", reason)
		if reason != 0 {
			releaseTrade()
		}
	})
	t.RegOnRspUserLogin(onLogin)
	t.ReqConnect(tradeFront)
	go func() {
		// 连接超时设置
		select {
		case <-chConnected:
		case <-time.After(10 * time.Second):
			fmt.Println("连接超时")
			releaseTrade()
			time.Sleep(5 * time.Second)
			reloginTimes++
			if reloginTimes >= 3 {
				reloginTimes = 0
				return
			}
			startTrade()
		}
	}()
}
func releaseTrade() {
	t.Release()
	t = ctp.NewTrade()
}

func onLogin(login *goctp.RspUserLoginField, info *goctp.RspInfoField) {
	logrus.Infof("trade login info: %v", info)
	if info.ErrorID == 7 { // 未初始化
		go func() {
			time.Sleep(1 * time.Minute) // 一分钟试一次
			t.ReqLogin(investorID, password, brokerID, appID, authCode)
		}()
	} else if info.ErrorID != 0 {
		go releaseTrade()
	} else {
		regTrade() // 注册交易相关事件
		startQuote()
	}
}
